﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace Vampirewal.Admin.Server.WebApi
{
    /// <summary>
    /// 自定义webapi返回值格式
    /// </summary>
    public class WebApiResultMiddleware : ActionFilterAttribute

    {

        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //根据实际需求进行具体实现
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;

                if (objectResult?.Value == null)
                {
                    context.Result = new ObjectResult(new { code = 404, errormsg = "未找到资源", msg = "", issuccess = false });
                }
                else
                {
                    context.Result = new ObjectResult(new { code = 200, msg = "", data = objectResult.Value , issuccess = true});
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new { code = 404, errormsg = "未找到资源", msg = "", issuccess = false });
            }
            else if (context.Result is ContentResult)
            {
                context.Result = new ObjectResult(new { code = 200, msg = "", data = ((ContentResult)context.Result).Content, issuccess = true });
            }
            else if (context.Result is StatusCodeResult)
            {
                context.Result = new ObjectResult(new { code = ((StatusCodeResult)context.Result).StatusCode, sub_msg = "", msg = "" });
            }

        }

    }
}
